package cn.ztuo.bitrade.controller;

import cn.ztuo.bitrade.entity.Coin;
import cn.ztuo.bitrade.entity.WithdrawRecord;
import cn.ztuo.bitrade.service.CoinService;
import cn.ztuo.bitrade.service.MemberWalletService;
import cn.ztuo.bitrade.service.WithdrawRecordService;
import cn.ztuo.bitrade.util.CoBoUtils;
import cn.ztuo.bitrade.util.MessageResult;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.TreeMap;

import static cn.ztuo.bitrade.util.BigDecimalUtils.div;

/**
 * cobo 回调接口
 */
@Slf4j
@RestController
@RequestMapping("/coboapi")
public class RechargeCcontroller {
    @Autowired
    private CoinService coinService;
    @Autowired
    private MemberWalletService walletService;
    @Autowired
    private CoBoUtils coBoUtils;

    @Autowired
    private WithdrawRecordService withdrawRecordService;


    @RequestMapping(value = "/getmessage",method = {RequestMethod.POST,RequestMethod.GET})
    public String coboRecharge(@RequestBody JSONObject jsonObject) {
        log.info("cobo回调接口传递的参数={}", jsonObject);
        String id = jsonObject.getString("id");
        log.info("cobo回调接口传递参数id={}", id);
        //判断id不为空
        if (!StringUtils.isEmpty(id)) {
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("id", id);
            try {
                JSONObject jSONObject = coBoUtils.transaction(params);
                log.info("根据id查询到的入账信息={}", jSONObject.toJSONString());
                //获取result里面的数据参数
                JSONObject result = jSONObject.getJSONObject("result");
                //enum(deposit / withdraw)	交易类型
                String side = result.getString("side");
                log.info("cobo推送的交易类型={}",side);
                if (side.equals("deposit")){
                    //币种代号
                    String coinStr = result.getString("coin");

                    // 标记变量 标记USDT类型 0:BTC  1:ETH
                    Integer coinPrefixFlag = null;
                    // 有前缀的币种特殊处理一下
                    if (coinStr.contains("_")){
                        String[] coinStrArray = coinStr.split("_");
                        String unitSuffix = coinStrArray[coinStrArray.length - 1];
                        if ("USDT".equals(unitSuffix)){
                            coinPrefixFlag = "BTC".equals(coinStrArray[0]) ? 0 : 1;
                        }
                        coinStr = unitSuffix;
                    }
                    Coin coin = coinService.findOne(coinStr);
                    coin.setUnit(coinStr);

                    //充值地址
                    String address = result.getString("address");
                    //区块链交易ID
                    String txid = result.getString("txid");
                    log.info("获取的币种配置表coin={}", coin);
                    if (coin != null && walletService.findDeposit(address, txid) == null) {
                        //交易数值大小 (注意这里的数值包含小数位, 例如BTC的decimal为8位，则这里的100000000实际为1个BTC)
                        BigDecimal amount = result.getBigDecimal("amount");
                        //获得数量除以精度取后八位
                        String withdrawScale = coinPrefixFlag != null && coinPrefixFlag == 0 ? coin.getWithdrawScale() + "00" : coin.getWithdrawScale();
                        BigDecimal div = div(amount, new BigDecimal(withdrawScale), 8);
                        MessageResult mr = walletService.recharge(coin, coinPrefixFlag,address, div, txid);
                        Long memberId = (Long) mr.getData();
                        log.info("memberId={}",memberId);
                        if (memberId>0){

                            return "ok";
                        }
                    }else {
                        log.info("该笔充值以冲入资产表={}",jSONObject.toJSONString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("查询入账信息失败={}", e);
            }

        } else {
            log.info("参数格式不正确={}", jsonObject);
        }


        return null;
    }

    /**
     * cobo提币回调
     * 弃用
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/coboWithdraw",method = {RequestMethod.POST,RequestMethod.GET})
    public String coboWithdraw(@RequestBody JSONObject jsonObject) {
        log.info("cobo提币回调接口传递的参数={}", jsonObject);
        String id = jsonObject.getString("id");
        // 判断id是否为null
        if (!StringUtils.isEmpty(id)){
            try {
                TreeMap<String, Object> params = new TreeMap<>();
                params.put("id",id);
                // 请求cobo 查询提币信息
                JSONObject withdrawData = coBoUtils.getWithdrawData(params);
                log.info("根据id查询到的提币信息={}", withdrawData.toJSONString());
                Boolean successStatus = withdrawData.getBoolean("success");
                // 提币成功处理
                if (successStatus){
                    JSONObject result = withdrawData.getJSONObject("result");
                    String address = result.getString("address");
                    String txid = result.getString("txid");
                    // 查询提币记录信息
                    WithdrawRecord withdrawRecord = withdrawRecordService.findByAddress(address);
                    // 提币成功处理
                    withdrawRecordService.withdrawSuccess(withdrawRecord.getId(), txid, "no");
                } else {
                    // 失败处理
                    log.info("====================== 提币失败 ==================================");
                    //自动转账失败，转为人工处理
//                    withdrawRecordService.withdrawFail(withdrawRecord.getId());
                }
                return "ok";
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.info("参数格式不正确={}", jsonObject);
        }

        return null;
    }
}
